import ButtonManager from './ButtonManager.js'; // 导入按钮管理模块

const BatchEnrollLongTermActivity = {
  buttonId: 'batchEnrollLongTermActivity', // 按钮 ID
  defaultText: '6. 一次性报名官方长期活动', // 默认按钮文本

  // 初始化函数
  init() {
    document.getElementById(this.buttonId).addEventListener('click', this.handleClick.bind(this)); // 绑定点击事件
  },

  // 点击事件处理函数
  async handleClick() {
    ButtonManager.updateButtonState(this.buttonId, '6. 一次性报名官方长期活动-处理中...', true); // 更新按钮状态为加载中
    ButtonManager.disableAllButtons(this.buttonId); // 禁用其他按钮

    try {
      const minimumLongActivityPrices = Number(minimumLongActivityPriceInput.value.trim());
      const minimumLongActivityPrice = Math.floor(minimumLongActivityPrices*100)
      console.log('报名长期活动',minimumLongActivityPrice)
      if(isNaN(minimumLongActivityPrice)){
        alert('请输入报名长期活动最低价格')
        return
      }


      if (minimumLongActivityPrice && minimumLongActivityPrice >= 5800) {
        console.log("输入的报名长期活动最低价格:", minimumLongActivityPrice);
        // 这里可以添加更多的逻辑，比如将报名长期活动最低价格存储到 localStorage 或者发送到后台脚本
      }else {
        alert('请输入报名长期活动最低价格/不能低于58')
        console.log('请输入报名长期活动最低价格/不能低于58')
        return
      }


      const { mallId, antiContent } = await new Promise((resolve) => {
        chrome.storage.local.get(['mallId', 'antiContent'], resolve); // 从本地存储获取 mallId 和 antiContent
      });

      if (!mallId || !antiContent) {
        console.error("mallId 或 antiContent 未找到"); // 检查是否获取到必要参数
        return;
      }

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); // 获取当前标签页

      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id }, // 注入脚本到当前标签页
        func: executeBatchEnrollLongTermActivity, // 执行报名长期活动逻辑
        args: [mallId, antiContent,minimumLongActivityPrice], // 传递参数
      });

      if (results && results[0] && results[0].result) {
        console.log("报名官方长期活动完成，返回数据:", results[0].result); // 输出报名长期活动结果
      } else {
        console.error("未获取到有效数据"); // 输出错误信息
      }
    } catch (error) {
      console.error("报名官方长期活动失败:", error); // 捕获错误
    } finally {
      ButtonManager.resetButtonState(this.buttonId, this.defaultText); // 恢复按钮状态
      ButtonManager.enableAllButtons(); // 启用所有按钮
    }
  },
};

// 报名长期活动逻辑函数
function executeBatchEnrollLongTermActivity(j_mallid, j_anti_content, j_smallPrice = 5800) {
  return new Promise((resolve, reject) => {
    console.log("开始执行一次性报名官方长期活动逻辑...");
    console.log("接收到的参数:", { j_mallid, j_anti_content });

    let j_activityArr = [{
      activityType: 1,
      activityId: 315707,
      smallPrice: j_smallPrice,
      name: '限时秒杀'
    },{
      activityType: 5,
      activityId: 323044,
      smallPrice: j_smallPrice,
      name:'官方大促'
    },{
      activityType: 27,
      activityId: 315792,
      smallPrice: j_smallPrice,
      name:'清仓甩卖'
    }];
    let j_activityIndex = 0;

    let j_time = Math.floor(Math.random() * 2) * 1000 + 1000;
    let j_body = {
      "activityType": 1,
      "rowCount": 50,
      "addSite": true,
      "productSkcExtCodes":[]
    };

    // let j_smallPrice = 5600; // 最小提交活动的价格

    let j_productList = [];
    let j_hasMore = false;
    let j_noRegistrationProductIdArr = []; // 没有可报名进行中的活动
    let j_registrationProductIdArr = []; // 可报名进行中的活动
    let j_total = 0;
    let j_successTotal = 0; // 报名成功数
    let j_pageindex = 0;
    let j_smallPriceArr = []; // 价格过低的数据

    function j_match() {
      if (j_activityIndex >= j_activityArr.length) {
        console.log('没有更多活动');
        alert('官方长期活动已完成')
        location.reload()
        return;
      }
      j_body.activityType = j_activityArr[j_activityIndex].activityType;

      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/gambit/marketing/enroll/scroll/match", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/activity/marketing-activity/detail-new?type=1',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(j_body),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          console.log('查询数量:' + j_total, '查询页数:' + j_pageindex);
          if (data.success) {
            j_body.searchScrollContext = data.result.searchScrollContext;
            j_hasMore = data.result.hasMore;

            j_pageindex++;
            if (data.result.matchList.length > 0) {
              j_productList = [];
              j_total += data.result.matchList.length;
              data.result.matchList.forEach((item, index) => {
                let skcListArr = [];
                item.skcList.forEach((itemSub, indexSub) => {
                  let siteActivityPriceList = [];
                  itemSub.sitePriceList.forEach((itemSubs, indexSubs) => {
                    if (itemSubs.suggestActivityPrice > j_activityArr[j_activityIndex].smallPrice) {
                      siteActivityPriceList.push({ activityPrice: itemSubs.suggestActivityPrice, siteId: itemSubs.siteId });
                    } else {
                      j_smallPriceArr.push({ skcid: itemSub.skcId, activityPrice: itemSubs.suggestActivityPrice });
                    }
                  });
                  let skuList = [];

                  itemSub.skuList.forEach((itemSubsku, indexSubsku) => {
                    skuList.push({
                      skuId: itemSubsku.skuId
                    });
                  });

                  if (siteActivityPriceList.length > 0 && skuList.length > 0) {
                    skcListArr.push({
                      skcId: itemSub.skcId,
                      siteActivityPriceList: siteActivityPriceList,
                      skuList: skuList
                    });
                  }
                });

                // if (j_activityArr[j_activityIndex].activityId === item.suggestEnrollSessionIdList[0] && skcListArr.length > 0) {

                if (skcListArr.length > 0) {
                  j_registrationProductIdArr.push(item.productId);

                  j_productList.push({
                    productId: item.productId,
                    activityStock: item.suggestActivityStock,
                    skcList: skcListArr,
                    sessionIds: item.suggestEnrollSessionIdList
                  });
                } else {
                  j_noRegistrationProductIdArr.push(item.productId); // 没有进行中的id
                }
              });

              if (j_productList.length > 0) {
                setTimeout(function () { j_submit(j_productList); }, j_time);
              } else {
                setTimeout(function () { j_match(); }, j_time);
              }
            } else if (j_hasMore) {
              console.log('还有更多');
              setTimeout(function () { j_match(); }, j_time);
            } else {
              if (j_activityArr.length > j_activityIndex) {
                console.log('报名' + j_activityArr[j_activityIndex].name + '已完成');
                j_activityIndex++;
                delete j_body.searchScrollContext;
                setTimeout(function () { j_match(); }, j_time);
              }
              console.log('没有进行中的活动' + j_activityIndex, j_noRegistrationProductIdArr.length, j_noRegistrationProductIdArr);
              console.log('进行中的活动报名成功' + j_activityIndex, j_registrationProductIdArr.length, j_registrationProductIdArr);
            }
          } else {
            console.log('报名限时秒杀查询失败', data.errorMsg);
            setTimeout(function () { j_match(); }, j_time);
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
        });
    }

    // 报名
    function j_submit(arr) {
      let submitbody = {
        "activityType": j_activityArr[j_activityIndex].activityType,
        "productList": arr
      };
      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/gambit/marketing/enroll/submit", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/activity/marketing-activity/detail-new?type=1',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(submitbody),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            j_successTotal += arr.length;
            console.log('累计报名成功:' + j_successTotal, '报名成功', arr.length, arr);
            setTimeout(function () { j_match(); }, j_time);
          } else {
            setTimeout(function () { j_submit(arr); }, j_time);
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
        });
    }

    // 开始执行逻辑
    j_match();
  });
}

export default BatchEnrollLongTermActivity; // 导出模块